package cn.itcast.controller;

import cn.itcast.exception.NameIsNullException;
import cn.itcast.exception.noAccountException;
import cn.itcast.pojo.Account;
import cn.itcast.service.Uservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private Uservice uservice;

    @RequestMapping("login")
    public String login(HttpSession session){
        session.setAttribute("meto","itheima");

        return "forward:/login.jsp";
    }
    @RequestMapping(value = "findAll")
    public String findAll(Model model){
        System.out.println("控制器方法执行");
        model.addAttribute("meto","Hello World");
        List<Account> accountList = uservice.findAll();
        model.addAttribute("accountList",accountList);
        return "list";
    }

    @RequestMapping("findByName")
    public String findByName(@RequestParam("name") String name,Model model) throws Exception {
        if(name  == null || "".equals(name)){
            throw new NameIsNullException("你输入的名字为空,请返回重新输入!!!!");
        }
        Account account = uservice.findByName(name);
        if (account == null){
            throw new noAccountException("没有你输入的账户,请重新输入!!!");
        }
        model.addAttribute("account",account);
        return "findAccount";
    }
    //
    @RequestMapping(value = "delete/{id}")
    public String delete(@PathVariable("id") Integer id){
        uservice.delete(id);
        return "deleteSuccess";
    }
    //增加的准备工作
    @RequestMapping("readlySave")
    public String readlySave(){
        return "addList";
    }
    //增加
    @RequestMapping("save")
    public String save(Account account,Model model){
        if(account.getName().equals(uservice.findByName(account.getName()).getName()) ){
            model.addAttribute("DBMesg","你存入的账户已经存在!!!");
            return "addList";
        }else {
        uservice.save(account);
        return "saveSuccess";
        }
    }
    //修改的准备
    @RequestMapping("updateReadly")
    public String updateReadly(Integer id,Model model){
        System.out.println(id);
        model.addAttribute("id", id);

        return "updateReadly2";
    }
    //修改
    @RequestMapping("update")
    public String update(Account account){
     uservice.update(account);
     return "updateSuccess";
    }
}
